package gr.handmademarket.ui.pages;

import gr.handmademarket.ui.WebHandMadeSession;
import gr.handmademarket.ui.views.PurchaseItemsListView;
import gr.handmademarket.util.PaymentUtils;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.pages.RedirectPage;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.Url;
import org.apache.wicket.request.resource.UrlResourceReference;



/**
 * page for displaying products of my basket.
 */
public class MyBasketPage 
extends CommonTemplatePage{

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 1L;
	
	private static final String PAYPAL_GIF_URL = "https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif";
	
	private static final String PAYPAL_LOGIN_URL = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=";
	
	/**
	 * the list view.
	 */
	private PurchaseItemsListView listView;
		
	/**
	 * Creates a new UploadPage object. 
	 *
	 */
	@SuppressWarnings("nls")
	public MyBasketPage(){
		super();
		WebHandMadeSession session = (WebHandMadeSession) WebHandMadeSession.get();
		listView = new PurchaseItemsListView("myProducts", session.getUserItems());
		add(listView);
		AjaxLink<Image> checkoutLink = createCheckoutLink(session.getTotalAmount());
		add(checkoutLink);
	}
	
	/**
	 * @return checkout link.
	 */
	@SuppressWarnings("nls")
	private AjaxLink<Image> createCheckoutLink(double totalAmount){
		final double localAmount = totalAmount;
		UrlResourceReference imageReference = 
				new UrlResourceReference(Url.parse(PAYPAL_GIF_URL));
		
		Image image = new Image("checkoutImg", imageReference);
		AjaxLink<Image> ajaxLink = new AjaxLink<Image>("checkoutLink", new Model<Image>(image)) {
			/**
			 * serialVersionUID
			 */
			private static final long serialVersionUID = 1L;

			@Override
			public void onClick(AjaxRequestTarget target) {
				PaymentUtils utils = new PaymentUtils();
				String token = utils.callSetExpressCheckout(localAmount);
				if (token != null){
					RedirectPage page = new RedirectPage(PAYPAL_LOGIN_URL+token);
					setResponsePage(page);
				}
			}
		};
		ajaxLink.add(image);
		return ajaxLink;
	}
	
	
}
